package com.example.demo.handler;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.PdfSaveOptions;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: lu
 * @Date: 2024-12-19-16:08
 * @Description:
 */
@Slf4j
public class WordHandler {



    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    //private static void getLicense() {
    //    String licenseFilePath = "word-license.xml";
    //    try {
    //        InputStream is = WordHandler.class.getClassLoader().getResourceAsStream(licenseFilePath);
    //        License license = new License();
    //        license.setLicense(Objects.requireNonNull(is));
    //    } catch (Exception e) {
    //        log.error("license verify failed");
    //        e.printStackTrace();
    //    }
    //}

    public static void wordToPdf1(HttpServletResponse response, String wordPath, String title) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String timeStamp = dateFormat.format(new Date());

        //getLicense();
        try {
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/pdf");
            String encodedFileName = URLEncoder.encode(title, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName+timeStamp + ".pdf");

            Document doc = new Document(wordPath);
            //pdf换行格式保存
            PdfSaveOptions options = new PdfSaveOptions();
            options.setPreserveFormFields(true);
            /*设置文档标题和作者*/
            doc.getBuiltInDocumentProperties().setTitle(title);
            doc.getBuiltInDocumentProperties().setAuthor("-");
            doc.save(response.getOutputStream(), SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
            e.printStackTrace();
        } finally {
            // 删除word文档的地址
            File file = new File(wordPath);
            if (file != null && file.isFile() && file.exists()) {
                file.delete();
            }
        }
    }


    /**
     * 删除下载到本地的临时图片
     *
     * @param
     */
    public static void deleteDownloadedFile(List<String> filePaths) {
        // 使用 Set 去重
        Set<String> uniquePaths = new HashSet<>(filePaths);
        try {
            for (String filePath : uniquePaths) {
                File fileToDelete = new File(filePath);
                if (fileToDelete.exists()) {
                    fileToDelete.setWritable(true); // 设置为可写模式
                    boolean deleted = fileToDelete.delete();
                    if (!deleted && fileToDelete.exists()) { // 如果删除失败且文件仍然存在
                        fileToDelete.deleteOnExit(); // 注册在 JVM 退出时删除
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("删除异常：" + e.getMessage(), e);
        }
    }
}
